import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Strategy, ExtractJwt } from 'passport-jwt';
import { UserEntity } from '@modules/user/entity/user.entity';
import config from '@config/config.default';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(
    @InjectRepository(UserEntity)
    private readonly userRepository: Repository<UserEntity>,
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: config.jwt.secret,
    });
  }

  async validate(payload: UserEntity) {
    const user = await this.userRepository.findOne({ where: { userId: payload.userId, password: payload.password } });
    if (!user) {
      return false;
    }
    return { userId: user.userId, username: payload.username };
  }
}
